package com.huobao.yunying.activitys;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huobao.yunying.adapters.Adapter_Jiesuan_;
import com.huobao.yunying.base.HuobaoBaseActivity;
import com.huobao.yunying.entity.Bonus_data;
import com.huobao.yunying.entity.Coupon_list;
import com.huobao.yunying.entity.Detailprice_intervals;
import com.huobao.yunying.entity.GouwucgeGoods;
import com.huobao.yunying.entity.Gouwuche_spec;
import com.huobao.yunying.entity.Gouwuche_specification;
import com.huobao.yunying.entity.JiesuanData;
import com.huobao.yunying.entity.Jiesuan_goods_info;
import com.huobao.yunying.entity.My_address;
import com.huobao.yunying.entity.Regions;
import com.huobao.yunying.entity.Shipping_methods;
import com.huobao.yunying.https.Http;
import com.huobao.yunying.https.HttpConst;
import com.huobao.yunying.https.HttpListener;
import com.huobao.yunying.https.HttpUtil;
import com.huobao.yunying.utils.SkipUtils;
import com.huobao.yunying.views.NoScrollListView;
import com.huobao.zhangying.R;

import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 结算页面
 */
public class Act_Jiesuan extends HuobaoBaseActivity implements OnClickListener, OnItemClickListener,OnCheckedChangeListener {

	// 所有的地区列表
	private List<Regions> m_AllRegions;
	// 选择的省
	private Regions m_Select_ShengRegion;
	// 选择的市
	private Regions m_Select_ShiRegion;
	/*************************************************/
	private String store_id;
	private String rec_id;
	private String id;

	/**********************************************/
	@ViewInject(R.id.tv_name)
	private TextView tv_name;
	@ViewInject(R.id.tv_tel)
	private TextView tv_tel;
	@ViewInject(R.id.tv_address)
	private TextView tv_address;
	@ViewInject(R.id.view_address)
	private View view_address;
	@ViewInject(R.id.view_has_address)
	private View view_has_address;
	@ViewInject(R.id.view_no_address)
	private View view_no_address;
	/*
	 * @ViewInject(R.id.listview_address) private NoScrollListView lv_address;
	 * private Adapter_Address adapter_address; // 使用新地址
	 * 
	 * @ViewInject(R.id.rb_new_address) private RadioButton rb_new_address; //
	 * 填写新地址的view
	 * 
	 * @ViewInject(R.id.view_add_address) private View view_add_address; // 国家
	 * 
	 * @ViewInject(R.id.tv_guojia) private TextView tv_guojia; // 省
	 * 
	 * @ViewInject(R.id.tv_sheng) private TextView tv_sheng; // 市
	 * 
	 * @ViewInject(R.id.tv_shi) private TextView tv_shi;
	 */
	/////////////////////////////////////////// 商品列表
	@ViewInject(R.id.ex_listview)
	private NoScrollListView listview;
	private Adapter_Jiesuan_ adapter;

	// 总价
	@ViewInject(R.id.tv_price)
	private TextView tv_price;

	////////////////////////////////// 新的地址
	/*
	 * @ViewInject(R.id.edt_shouhuoren) private EditText edt_shouhuoren;
	 * 
	 * @ViewInject(R.id.edt_shoujihao) private EditText edt_shoujihao;
	 * 
	 * @ViewInject(R.id.edt_dianhua) private EditText edt_dianhua;
	 * 
	 * @ViewInject(R.id.edt_xiangxi) private EditText edt_xiangxi;
	 * 
	 * @ViewInject(R.id.edt_youbian) private EditText edt_youbian;
	 */

	// 地址id
	private String addr_id;

	@ViewInject(R.id.scrollview)
	private ScrollView scrollview;
	
	
	@ViewInject(R.id.checkbox)
	private CheckBox checkbox;
	//红包sn
	private Bonus_data bonus_data;

	//立即支付
	private boolean isQuit;
	private String spec_id;
	private String quantity;

	@Override
	protected int getContentView() {
		return R.layout.layout_jiesuan;
	}

	@Override
	protected String getTitleText() {
		return "订单确认";
	}

	@Override
	protected void init() {
		getIntentData();
		// adapter_address = new Adapter_Address(context, rb_new_address,
		// view_add_address);
		// lv_address.setAdapter(adapter_address);
		// lv_address.setOnItemClickListener(this);
		// tv_guojia.setOnClickListener(this);
		// tv_sheng.setOnClickListener(this);
		// tv_shi.setOnClickListener(this);

		checkbox.setOnCheckedChangeListener(this);
		view_address.setOnClickListener(this);
		adapter = new Adapter_Jiesuan_(context, tv_price);
		listview.setAdapter(adapter);
		jiesuan();
	}

	private void getIntentData() {
		Intent intent = getIntent();
		isQuit = intent.getBooleanExtra("isQuit",false);
		store_id = intent.getStringExtra("store_id");
		rec_id = intent.getStringExtra("rec_id");
		id = intent.getStringExtra("id");

		spec_id = intent.getStringExtra("spec_id");
		quantity = intent.getStringExtra("quantity");
	}

	private My_address address;

	private void jiesuan() {
		Map<String, String> map;
		if(isQuit){
			map = HttpUtil.getParams(HttpConst.FRIST_KEY, "order","act","settlement", "goods", "immediately", "store_id",
					store_id, "spec_id", spec_id, "id", id,"quantity",quantity);
		}else{
			map = HttpUtil.getParams(HttpConst.FRIST_KEY, "order", "goods", "cart", "store_id",
					store_id, "rec_id", rec_id, "id", id);
		}

		Http.getInstant().sendRequest(context, map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				jsonObject = jsonObject.getJSONObject("retval");
				// 数据1
				JiesuanData jiesuanData = JSON.parseObject(jsonObject.toJSONString(), JiesuanData.class);
				adapter.setJiesuanData(jiesuanData);
				// 我的地址
				List<My_address> myAddress = JSON.parseArray(jsonObject.getString("my_address"), My_address.class);
				if (myAddress != null && myAddress.size() > 0) {
					// adapter_address.addAll(myAddress);
					address = myAddress.get(0);
					addr_id = myAddress.get(0).addr_id;
					tv_name.setText(myAddress.get(0).consignee);
					tv_tel.setText(myAddress.get(0).phone_tel);
					tv_address.setText(myAddress.get(0).region_name + myAddress.get(0).address);
					view_has_address.setVisibility(View.VISIBLE);
					view_no_address.setVisibility(View.GONE);
				} else {
					view_has_address.setVisibility(View.GONE);
					view_no_address.setVisibility(View.VISIBLE);
				}
				// 所有的地区列表
				m_AllRegions = new ArrayList<Regions>();
				JSONArray array = jsonObject.getJSONArray("regions");
				for (int i = 0; i < array.size(); i++) {
					JSONObject object = array.getJSONObject(i);
					Regions regions = new Regions();
					regions.region_id = object.getString("region_id");
					regions.region_name = object.getString("region_name");
					regions.children = JSON.parseArray(object.getString("children"), Regions.class);
					m_AllRegions.add(regions);
				}

				// 数据
				List<Jiesuan_goods_info> goods_infos = new ArrayList<Jiesuan_goods_info>();
				JSONArray goods_info_array = jsonObject.getJSONArray("goods_info");
				for (int i = 0; i < goods_info_array.size(); i++) {
					JSONObject object = goods_info_array.getJSONObject(i);
					Jiesuan_goods_info jiesuan_goods_info = JSON.parseObject(object.toJSONString(),
							Jiesuan_goods_info.class);

					// 货运方式
					List<Shipping_methods> list = new ArrayList<Shipping_methods>();
					JSONArray shipping_methods_array = object.getJSONArray("shipping_methods");
					for (int k = 0; k < shipping_methods_array.size(); k++) {
						JSONObject jsonObject2 = shipping_methods_array.getJSONObject(k);
						Shipping_methods shipping_methods = new Shipping_methods();
						shipping_methods.name = jsonObject2.getString("name");
						shipping_methods.fees_id = jsonObject2.getString("fees_id");
						shipping_methods.data = JSON.parseArray(jsonObject2.getString("data"), String.class);
						list.add(shipping_methods);
					}
					jiesuan_goods_info.shipping_methods = list;

					// 优惠券信息
					List<Coupon_list> list11 = new ArrayList<Coupon_list>();
					JSONArray coupon_list_array = object.getJSONArray("coupon_list");
					if (coupon_list_array != null)
						for (int k = 0; k < coupon_list_array.size(); k++) {
							JSONObject jsonObject2 = coupon_list_array.getJSONObject(k);
							Coupon_list coupon_list = new Coupon_list();
							coupon_list.coupon_sn = jsonObject2.getString("coupon_sn");
							coupon_list.store_id = jsonObject2.getString("store_id");
							coupon_list.coupon_id = jsonObject2.getString("coupon_id");
							coupon_list.coupon_name = jsonObject2.getString("coupon_name");
							coupon_list.coupon_value = jsonObject2.getString("coupon_value");
							list11.add(coupon_list);
						}
					jiesuan_goods_info.coupon_list = list11;

					// 每种货运方式对应的运费
					List<Float> floats = JSON.parseArray(object.getString("store_freight"), Float.class);
					jiesuan_goods_info.store_freight = floats;
					// 商品信息

					List<GouwucgeGoods> goodsss = new ArrayList<GouwucgeGoods>();
					JSONArray jsonArray = object.getJSONArray("goods_info");
					for (int j = 0; j < jsonArray.size(); j++) {
						JSONObject goosObject = jsonArray.getJSONObject(j);
						GouwucgeGoods goods = new GouwucgeGoods();
						goods.rec_id = goosObject.getString("rec_id");
						goods.user_id = goosObject.getString("user_id");
						goods.session_id = goosObject.getString("session_id");
						goods.store_id = goosObject.getString("store_id");
						goods.goods_id = goosObject.getString("goods_id");
						goods.goods_name = goosObject.getString("goods_name");
						goods.spec_id = goosObject.getString("spec_id");
						goods.price = goosObject.getString("price");
						goods.quantity = goosObject.getIntValue("quantity");
						goods.goods_image = goosObject.getString("goods_image");
						goods.group_id = goosObject.getString("group_id");
						goods.old_price = goosObject.getString("old_price");
						goods.store_name = goosObject.getString("store_name");
						goods.subtotal = goosObject.getFloatValue("subtotal");
						goods.is_collect = goosObject.getIntValue("is_collect");
						goods.price_intervals_count = goosObject.getIntValue("price_intervals_count");
						goods.indemnity = goosObject.getBooleanValue("indemnity");
						goods.weight = goosObject.getString("weight");
						goods.unit = goosObject.getString("unit");
						List<Gouwuche_specification> specifications = new ArrayList<Gouwuche_specification>();
						JSONArray specificationArray = goosObject.getJSONArray("specification");
						if (specificationArray != null) {
							for (int k = 0; k < specificationArray.size(); k++) {
								JSONObject specificationObject = specificationArray.getJSONObject(k);
								Gouwuche_specification specification = new Gouwuche_specification();
								specification.spec_id = specificationObject.getString("spec_id");
								specification.spec_1 = specificationObject.getString("spec_1");
								specification.price = specificationObject.getFloatValue("price");
								specification.spec = JSON.parseArray(specificationObject.getString("spec"),
										Gouwuche_spec.class);
								specifications.add(specification);
							}
						}
						goods.specification = specifications;
						if (goosObject.getString("quantitydesc") != null
								&& goosObject.getString("quantitydesc").equals("null") == false
								&& goosObject.getString("quantitydesc").equals("") == false) {
							goods.quantitydesc = JSON.parseArray(goosObject.getString("quantitydesc"), String.class);
						}

						goods.price_intervals = JSON.parseArray(goosObject.getString("price_intervals"),
								Detailprice_intervals.class);
						goodsss.add(goods);
					}
					jiesuan_goods_info.goods = goodsss;
					goods_infos.add(jiesuan_goods_info);
				}
				try {
					bonus_data = JSON.parseObject(jsonObject.getString("bonus_data"), Bonus_data.class);	
				} catch (Exception e) {
					bonus_data = null;
				}
				
				if(bonus_data != null && bonus_data.min_amount < jiesuanData.amount){
					//显示
					checkbox.setVisibility(View.VISIBLE);
					checkbox.setText("  满"+bonus_data.min_amount+"元可用红包"+bonus_data.bonus_value+"元");
				}else{
					checkbox.setVisibility(View.GONE);
				}
				adapter.clear();
				adapter.addAll(goods_infos);
				tv_price.setText((jiesuanData.amount + jiesuanData.freight) + "");
				scrollview.smoothScrollTo(0, 0);
			}

			@Override
			public void onHttpError(String error) {
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		// case R.id.tv_guojia:
		// SelectAreaPopupWindow.showPop(context, null, v, new
		// ItemClickImpl(1));
		// break;
		// case R.id.tv_sheng:
		// SelectAreaPopupWindow.showPop(context, m_AllRegions, v, new
		// ItemClickImpl(2));
		// break;
		// case R.id.tv_shi:
		// SelectAreaPopupWindow.showPop(context, m_Select_ShengRegion.children,
		// v, new ItemClickImpl(3));
		// break;
		case R.id.view_address:
			Intent intent = new Intent(this, Act_Manager_Address.class);
			intent.putExtra("data", address);
			intent.putExtra("flag", true);
			startActivityForResult(intent, 1);
			break;
		}
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		if (arg0 == 1) {
			My_address address = null;
			try {
				address = (My_address) arg2.getSerializableExtra("data");
			} catch (Exception e) {
			}
			if (address != null) {
				addr_id = address.addr_id;
				tv_name.setText(address.consignee);
				tv_tel.setText(address.phone_tel);
				tv_address.setText(address.region_name + address.address);
				view_has_address.setVisibility(View.VISIBLE);
				view_no_address.setVisibility(View.GONE);
			} else {
				jiesuan();
			}

		}
		super.onActivityResult(arg0, arg1, arg2);
	}

	// private class ItemClickImpl implements OnItemClickListener {
	//
	// private int type;
	//
	// public ItemClickImpl(int type) {
	// this.type = type;
	// }
	//
	// @Override
	// public void onItemClick(AdapterView<?> parent, View view, int position,
	// long id) {
	// SelectAreaPopupWindow.dismiss();
	// switch (type) {
	// case 1:
	// tv_guojia.setText("中国");
	// tv_sheng.setVisibility(View.VISIBLE);
	// break;
	// case 2:
	// for (Regions regions : m_AllRegions) {
	// regions.isSelect = false;
	// }
	// Regions regions_sheng = m_AllRegions.get(position);
	// regions_sheng.isSelect = true;
	// if (m_Select_ShengRegion != null &&
	// m_Select_ShengRegion.equals(regions_sheng) == false) {
	// // 变换了省
	// m_Select_ShiRegion = null;
	// tv_shi.setText("请选择...");
	// }
	// m_Select_ShengRegion = regions_sheng;
	// tv_sheng.setText(regions_sheng.region_name);
	// if (regions_sheng.children != null && regions_sheng.children.size() > 0)
	// {
	// tv_shi.setVisibility(View.VISIBLE);
	// } else {
	// tv_shi.setVisibility(View.GONE);
	// }
	// break;
	// case 3:
	// for (Regions regions : m_Select_ShengRegion.children) {
	// regions.isSelect = false;
	// }
	// Regions regions_shi = m_Select_ShengRegion.children.get(position);
	// regions_shi.isSelect = true;
	// m_Select_ShiRegion = regions_shi;
	// tv_shi.setText(regions_shi.region_name);
	// break;
	// }
	// }
	// }

	/**
	 * 立即结算
	 * 
	 * @param view
	 */
	public void onJiesuanCLick(View view) {
		// if (rb_new_address.isChecked()) {
		// // 使用新的地址
		// String consignee = edt_shouhuoren.getText().toString().trim();
		// String phone_mob = edt_shoujihao.getText().toString().trim();
		// String phone_tel = edt_dianhua.getText().toString().trim();
		// String address = edt_xiangxi.getText().toString().trim();
		// String zipcode = edt_youbian.getText().toString().trim();
		// if (TextUtils.isEmpty(consignee)) {
		// Toast.makeText(context, "收货人不能为空", Toast.LENGTH_SHORT).show();
		// return;
		// }
		// if (TextUtils.isEmpty(phone_mob)) {
		// Toast.makeText(context, "手机号码不能为空", Toast.LENGTH_SHORT).show();
		// return;
		// }
		// if (TextUtils.isEmpty(address)) {
		// Toast.makeText(context, "详细地址不能为空", Toast.LENGTH_SHORT).show();
		// return;
		// }
		// String region_id = m_Select_ShiRegion == null ?
		// m_Select_ShengRegion.region_id
		// : m_Select_ShiRegion.region_id;
		// String region_name = m_Select_ShiRegion == null ? "中国 " +
		// m_Select_ShengRegion.region_name
		// : "中国 " + m_Select_ShengRegion.region_name +
		// m_Select_ShiRegion.region_name;
		// Map<String, String> map = HttpUtil.getParams("app", "order", "act",
		// "saveaddress", "consignee", consignee,
		// "phone_mob", phone_mob, "phone_tel", phone_tel, "address", address,
		// "zipcode", zipcode, "region_id",
		// region_id, "region_name", region_name);
		// Http.getInstant().sendRequest(context, map, new HttpListener() {
		//
		// @Override
		// public void onHttpSuccess(String result) {
		// JSONObject jsonObject = JSON.parseObject(result);
		// jsonObject = jsonObject.getJSONObject("retval");
		// addr_id = jsonObject.getString("addr_id");
		// submitJiesuan();
		// }
		//
		// @Override
		// public void onHttpError(String error) {
		//
		// }
		// });
		// } else {
		//
		submitJiesuan();
		// }
	}

	private void submitJiesuan() {
		if (addr_id == null || addr_id.equals("")) {
			Toast.makeText(context, "请选择或新增收货地址", Toast.LENGTH_SHORT).show();
			return;
		}
		JSONObject shipping_id_json = new JSONObject();
		JSONObject postscript_json = new JSONObject();
		JSONObject is_free_fee_json = new JSONObject();
		JSONObject couponObject = new JSONObject();
		StringBuffer spec_id_buffer = new StringBuffer();
		StringBuffer quantity_buffer = new StringBuffer();
		for (Jiesuan_goods_info info : adapter.getList()) {
			EditText editText = info.liuyan_edt;
			postscript_json.put(info.store_id, editText.getText().toString().trim());
			is_free_fee_json.put(info.store_id, info.is_free_fee ? 1 : 0);
			if (info.shipping_methods != null && info.shipping_methods.size() != 0) {
				for (Shipping_methods methods : info.shipping_methods) {
					if (methods.isSelect) {
						shipping_id_json.put(info.store_id, methods.fees_id);
						break;
					}
				}
			}
			if(info.coupon_list != null && info.coupon_list.size() != 0){
				for(Coupon_list coupon_list : info.coupon_list){
					if(coupon_list.isSelect){
						couponObject.put(coupon_list.store_id, coupon_list.coupon_sn);
					}
				}
			}

			List<GouwucgeGoods> goods = info.goods;
			for(GouwucgeGoods gd : goods){

				if(gd.spec_id.equals("0")){
					List<Gouwuche_specification> specification = gd.specification;
					for(Gouwuche_specification gs : specification){
						if(gs.spec!= null && gs.spec.size()!=0){
							for(Gouwuche_spec sp : gs.spec){
								spec_id_buffer.append(sp.spec_id);
								spec_id_buffer.append(",");
								quantity_buffer.append(sp.num);
								quantity_buffer.append(",");
							}
						}else{

						}
					}
				}else{
					spec_id_buffer.append(gd.spec_id);
					spec_id_buffer.append(",");
					quantity_buffer.append(gd.quantity);
					quantity_buffer.append(",");
				}
			}
		}
		String spec_id = spec_id_buffer.toString().substring(0, spec_id_buffer.length()-1);
		String quantity = quantity_buffer.toString().substring(0, quantity_buffer.length()-1);
		Map<String, String> map;
		if(isQuit){
			if(checkbox.isChecked() && bonus_data != null){
				map = HttpUtil.getParams("app", "order", "goods", "immediately", "act", "checkorder", "addr_id",
						addr_id, "store_id", store_id, "rec_id", TextUtils.isEmpty(rec_id) ? "0" : rec_id, "id", id, "shipping_id", shipping_id_json.toString(),
						"postscript", postscript_json.toString(), "is_free_fee", is_free_fee_json.toString(),"coupon_id",couponObject.toString(),"bonus_sn",bonus_data.bonus_sn,"spec_id",spec_id,"quantity",quantity);
			}else{
				map = HttpUtil.getParams("app", "order", "goods", "immediately", "act", "checkorder", "addr_id",
						addr_id, "store_id", store_id, "rec_id", TextUtils.isEmpty(rec_id) ? "0" : rec_id, "id", id, "shipping_id", shipping_id_json.toString(),
						"postscript", postscript_json.toString(), "is_free_fee", is_free_fee_json.toString(),"coupon_id",couponObject.toString(),"spec_id",spec_id,"quantity",quantity);
			}
		}else{
			if(checkbox.isChecked() && bonus_data != null){
				map = HttpUtil.getParams("app", "order", "goods", "cart", "act", "checkorder", "addr_id",
						addr_id, "store_id", store_id, "rec_id", TextUtils.isEmpty(rec_id) ? "0" : rec_id, "id", id, "shipping_id", shipping_id_json.toString(),
						"postscript", postscript_json.toString(), "is_free_fee", is_free_fee_json.toString(),"coupon_id",couponObject.toString(),"bonus_sn",bonus_data.bonus_sn,"spec_id",spec_id,"quantity",quantity);
			}else{
				map = HttpUtil.getParams("app", "order", "goods", "cart", "act", "checkorder", "addr_id",
						addr_id, "store_id", store_id, "rec_id", TextUtils.isEmpty(rec_id) ? "0" : rec_id, "id", id, "shipping_id", shipping_id_json.toString(),
						"postscript", postscript_json.toString(), "is_free_fee", is_free_fee_json.toString(),"coupon_id",couponObject.toString(),"spec_id",spec_id,"quantity",quantity);
			}
		}

		Http.getInstant().sendRequest(context, map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				String str = jsonObject.getString("retval");
				getOrderAndAmont(str);
			}

			@Override
			public void onHttpError(String error) {

			}
		});
	}

	protected void getOrderAndAmont(String str) {
		Map<String, String> map = HttpUtil.getParams("app", "cashier", "order_id", str);
		Http.getInstant().sendRequest(context, map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				jsonObject = jsonObject.getJSONObject("retval");
				String order_amount = jsonObject.getString("order_amount");
				String order_sn = jsonObject.getString("order_sn");
				SkipUtils.Pay(context, order_sn, order_amount, "购买商品");
				finish();
			}

			@Override
			public void onHttpError(String error) {

			}
		});
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// My_address address = adapter_address.getItem(position);
		// addr_id = address.addr_id;
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		String price = tv_price.getText().toString().trim();
		if(TextUtils.isEmpty(price))return;
		float f = Float.parseFloat(price);
		float newF = 0;
		if(isChecked){
			newF = f - (bonus_data == null ? 0 : bonus_data.bonus_value);
		}else{
			newF = f + (bonus_data == null ? 0 : bonus_data.bonus_value);
		}
		tv_price.setText(newF+"");
	}
}
